//
//  YYERefreshControl.swift
//  weibo14
//
//  Created by mac on 16/3/9.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

enum  YYERefreshControlState: Int {
    
    case Normal = 0, Pulling,Refreshing
    
}
let YYERefreshControlH:CGFloat = 50

class YYERefreshControl: UIControl {

 
    // 当前控件观察的对象 (一般来说都是父控件)
    weak var scrollView: UIScrollView?


    var RefreshControlState:YYERefreshControlState = .Normal {
    
        didSet {
        
            if RefreshControlState == .Normal {
            
                indicatorView.stopAnimating()

                arrowImage.hidden = false
                
                messageLable.text = "下拉刷新数据哦"
                
                UIView.animateWithDuration(0.3, animations: { () -> Void in
                    
                    self.arrowImage.transform = CGAffineTransformIdentity
                    
                })
//// ///////////////////////////////////////////////////////////////////////
                
                if oldValue == .Refreshing {
                    // 判断上一次状态是刷新中状态,那么进入到Normal状态就需要去减去InsetTop
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.scrollView?.contentInset.top -= YYERefreshControlH
                    })
                }

/// ///////////////////////////////////////////////////////////////////////
            }
            
            if RefreshControlState == .Pulling {
            
                indicatorView.stopAnimating()

                arrowImage.hidden = false
                
                messageLable.text = "释放即可加载数据"
                
                UIView.animateWithDuration(0.3, animations: { () -> Void in
                    
                    self.arrowImage.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))

                })
            }
            
            if RefreshControlState == .Refreshing {
            
                indicatorView.startAnimating()
                
                arrowImage.hidden = true
            
                messageLable.text = "正在属性数据啊"
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.scrollView?.contentInset.top += YYERefreshControlH
                })

                //--------------类似于通知
                sendActionsForControlEvents(UIControlEvents.ValueChanged)

            }
        }
    
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI() {
    
        self.backgroundColor = UIColor.purpleColor()
        frame.size = CGSize(width: SCREENW, height: YYERefreshControlH)
        frame.origin.y = -YYERefreshControlH
        
        // 添加子控件
        addSubview(indicatorView)
        addSubview(arrowImage)
        addSubview(messageLable)
        
        // 添加约束
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowImage)
        }
        arrowImage.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-30)
        }
        messageLable.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.leading.equalTo(arrowImage.snp_trailing)
        }
        
        
        
    }
    // 结束刷新要调用的方法
    func endRefreshing(){
        
        RefreshControlState = .Normal
        
    }

    
    // 将要移动到某个父控件上的时候,就会调用该方法  用于拿到父控件

    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
//        print(newSuperview)
        
        if let scrollView = newSuperview as? UIScrollView {
        
            // 添加kvo
            scrollView.addObserver(self, forKeyPath: "contentOffset", options:[.Old,.New], context: nil)
            
            self.scrollView = scrollView
        }
    }
    
    // 去监听kvo 的改变
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {

        // "contentOffset",change:["old": NSPoint: {0, -64}, "new": NSPoint: {0, -64}, "kind": 1]
        // 在这里面 去改变状态
        
        let contentInsetTop = scrollView?.contentInset.top //   64
        let contentOffsetY = scrollView?.contentOffset.y   // - 64
   
       // 当空间改变这么多 说明完全露出来了
        let conditionValue = -YYERefreshControlH - contentInsetTop!

        
        if scrollView!.dragging {  //正在拖动 无非是nomal pull --
        
            // --- 先进这里
            if contentOffsetY < conditionValue && RefreshControlState == .Normal {
            
                RefreshControlState = .Pulling
                print("准备了!!")
                
                
            } else if RefreshControlState == .Pulling && contentOffsetY > conditionValue {
            
            
                RefreshControlState = .Normal
                print("下啦把")
            }
            
        } else { //松手了  偏移够大才出来
        
            if contentOffsetY < conditionValue && RefreshControlState == .Pulling {
            
                RefreshControlState = .Refreshing
                print("松手了 !!!!")
            }
            
        }
        
        
//        // dragging 是代表是否在被用户拖动
//        if scrollView!.dragging {
//            // 如果当前的contentOffset.y小于或者等于conditionValue,那么就代表当前控件完全显示出来
//            // 如果上面条件满足,并且当前状态是默认状态,那么就进入到 松手就刷新的状态(.Pulling)
//            if contentOffsetY <= conditionValue && refreshState == .Normal {
//                refreshState = .Pulling
//                print("松手就刷新")
//            }else if refreshState == .Pulling && contentOffsetY > conditionValue{
//                // 如果当前是松手就刷新状态,用户不松,把控件推回去.那么就设置当前状态为 .Normal
//                // 在这儿要设置成 normal
//                refreshState = .Normal
//                print("进入默认状态")
//            }
//        }else{
//            // 如果用户松手并且如果当前状态是Pulling状态,就进入到 Refreshing状态
//            if refreshState == .Pulling {
//                refreshState = .Refreshing
//                print("进入刷新状态")
//            }
//        }
        
    }
    
    
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    // MARK: 懒加载空间
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle:.White)
    
    private lazy var arrowImage: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))

    private lazy var messageLable:UILabel = {
    
        let lable: UILabel = UILabel(textColor: UIColor.grayColor(), fontSzie: 14)
        
        lable.text = "下拉刷新数据哦"
        
        lable.textAlignment = .Center
        
        return lable
    }()

}
